package com.keepers.repair.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.keepers.repair.R;
import com.keepers.repair.helper.SoundPlayerHelper;
import com.keepers.repair.net.LogUtil;
import com.keepers.repair.service.RecordingService;
import com.keepers.repair.utils.AlertToast;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * auth aboom
 * date 2018/10/28
 */
public class IntercomButton extends AppCompatButton {

    private boolean            isStart;
    private OnIntercomListener onIntercomListener;
    private Disposable         subscribe;

    private boolean isIntercomRecording;
    private boolean isNetworkConnected = true;

    public IntercomButton(Context context) {
        this(context, null);
    }

    public IntercomButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IntercomButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setBackgroundResource(R.drawable.ic_btn_talk_idle);
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ((RecordingService.RecBinder) service).setListener(new OnIntercomListener() {
                @Override
                public void onStartRecord() {
                    if (onIntercomListener != null) {
                        onIntercomListener.onStartRecord();
                    }
                }

                @Override
                public void onFinishedRecord(String audioPath, long millis) {
                    if (onIntercomListener != null) {
                        onIntercomListener.onFinishedRecord(audioPath, millis);
                    }
                }

                @Override
                public void onTimeShort() {
                    if (onIntercomListener != null) {
                        onIntercomListener.onTimeShort();
                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    public void setNetworkConnected(boolean networkConnected) {
        isNetworkConnected = networkConnected;
        networkUI();
    }

    private void networkUI() {
        if (isNetworkConnected) {
            setBackgroundResource(R.drawable.ic_btn_talk_idle);
        } else {
            setBackgroundResource(R.drawable.ic_btn_talk_none);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isNetworkConnected) {
            return true;
        }
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                if (isIntercomRecording) {
                    AlertToast.show("当前正在播放语音...");
                } else {
                    setBackgroundResource(R.drawable.ic_btn_talk_speak);
                    if (!isStart) {
                        isStart = true;
                        SoundPlayerHelper.callOutBegin(getContext());
                        RecordingService.starter((Activity) getContext(), serviceConnection, true);
                        subscribe = countdown(60).subscribe(integer -> {
                            LogUtil.e("录音时间 = " + integer);
                            if (integer == 0) {
                                stopRecording();
                                AlertToast.show("单次讲话限时60秒...");
                            }
                        });
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if (!isIntercomRecording) {
                    stopRecording();
                }

                break;
            default:
                break;
        }
        return true;
    }

    private void stopRecording() {
        if (subscribe != null && !subscribe.isDisposed()) {
            subscribe.dispose();
        }
        networkUI();
        if (isStart) {
            isStart = false;
            SoundPlayerHelper.callOutEnd(getContext());
            RecordingService.starter((Activity) getContext(), serviceConnection, false);
        }
    }

    public void setOnIntercomListener(OnIntercomListener onIntercomListener) {
        this.onIntercomListener = onIntercomListener;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (subscribe != null && !subscribe.isDisposed()) {
            subscribe.dispose();
        }
    }

    /**
     * rx执行倒计时
     *
     * @param time 秒数
     */
    public Observable<Integer> countdown(int time) {
        if (time < 0) {
            time = 0;
        }
        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
                .map(increaseTime -> countTime - increaseTime.intValue())
                .take(countTime + 1);
    }


    public void setIntercomRecording(boolean intercomRecording) {
        isIntercomRecording = intercomRecording;
    }
}


